package org.egomsl.mw.benchmark;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.egomsl.mw.HadoopRecord;
import org.egomsl.mw.mapreduce.ABaseInputFormat;

import java.io.IOException;

public class ABaseMapReduce {

    public static class ABaseMapper extends
            Mapper<BytesWritable, HadoopRecord, BytesWritable, IntWritable> {
        public void map(BytesWritable key, HadoopRecord value, Context output)
                throws IOException, InterruptedException {

            output.write(key, new IntWritable(1));
        }
    }

    public static class ABaseReducer extends Reducer<BytesWritable, IntWritable, Text, IntWritable> {

        // 实现具体mreduce业务逻辑
        @Override
        public void reduce(BytesWritable key, Iterable<IntWritable> values,
                           Context output)
                throws IOException, InterruptedException {
            int count = 0;
            for(IntWritable record:values) {
                count ++;
            }
            output.write(new Text(key.getBytes()), new IntWritable(count));
        }
    }

    public static void main(String args[]) throws Exception {

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf, "ABaseTask");

        job.setJarByClass(ABaseMapReduce.class);

        job.setMapperClass(ABaseMapper.class);
        job.setReducerClass(ABaseReducer.class);

        job.setInputFormatClass(ABaseInputFormat.class);

        job.setMapOutputKeyClass(BytesWritable.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(BytesWritable.class);
        job.setOutputValueClass(IntWritable.class);

        ABaseInputFormat.setTablePath(job, args[0]);
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.waitForCompletion(true);
    }
}
